
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:path_provider/path_provider.dart';

import '../bean/book.dart';
import 'get_path/get_base_path.dart';
import 'import_book.dart';

class AssetsToFileUtils{



  static Future<File> saveEpubToFile(Uint8List bytes) async {
    // 获取临时目录
    final directory = await getTemporaryDirectory();
    // 创建文件路径
    final filePath = '${directory.path}/贫穷的本质：我们为什么摆脱不了贫穷.epub';
    // 创建文件并写入数据
    final file = File(filePath);
    await file.writeAsBytes(bytes);
    return file;
  }

  static Future<Uint8List> getEpubBytes(BuildContext context) async {
    try {
      // 获取asset文件路径
      final ByteData data = await DefaultAssetBundle.of(
        context,
      ).load('assets/epub/贫穷的本质：我们为什么摆脱不了贫穷.epub');
      final bytes = data.buffer.asUint8List();
      return bytes;
    } catch (e) {
      throw Exception('读取文件失败: $e');
    }
  }

  static Future<File> readAndSaveEpub(BuildContext context) async {
    // 读取EPUB文件内容
    final bytes = await getEpubBytes(context);
    // 将内容保存为文件
    final file = await saveEpubToFile(bytes);
    return file;
  }

  static Future<Book> saveBook(
      File file,
      String title,
      String author,
      String description,
      String cover, {
        Book? provideBook,
      }) async {
    final newBookName =
    '${title.length > 20 ? title.substring(0, 20) : title}-${DateTime.now().millisecondsSinceEpoch}'
        .replaceAll(RegExp(r'[<>:"/\\|?*]'), '_')
        .replaceAll('\n', '')
        .replaceAll('\r', '')
        .trim();

    final extension = file.path.split('.').last;
    final dbFilePath = 'file/$newBookName.$extension';
    final filePath = getBasePath(dbFilePath);
    String? dbCoverPath = 'cover/$newBookName';
    // final coverPath = getBasePath(dbCoverPath);
    await file.copy(filePath);
    // remove cached file
    file.delete();
    dbCoverPath = await saveImageToLocal(cover, dbCoverPath);

    // {title: 贫穷的本质：我们为什么摆脱不了贫穷,
    // cover_path: cover/贫穷的本质：我们为什么摆脱不了贫穷-1744103286741.jpeg,
    // file_path: file/贫穷的本质：我们为什么摆脱不了贫穷-1744103286741.epub,
    // last_read_position: ,
    // reading_percentage: 0.0,
    // author: ( 印度) 班纳吉, （法）迪弗洛,
    // is_deleted: 0, description: null, rating: 0.0, group_id: 0,
    // create_time: 2025-04-08T17:08:06.799288, update_time: 2025-04-08T17:08:06.799289}



    Book book = Book(
        id: 1,
        title: title,
        coverPath: dbCoverPath,
        filePath: dbFilePath,
        lastReadPosition: '',
        readingPercentage: 0,
        author: author,
        isDeleted: false,
        rating: 0.0,
        createTime: DateTime.now(),
        updateTime: DateTime.now());
  print("=====电子书信息=====${book.toMap()}");
    // book.id = await insertBook(book);
    // BuildContext context = navigatorKey.currentContext!;
    // AnxToast.show(L10n.of(context).service_import_success);
    // headlessInAppWebView?.dispose();
    // headlessInAppWebView = null;
    return book;
  }


}




